var app = getApp()
var fun = require('../fun.js');
var QQMapWX = require('../mapsdk.js');
var qqmapsdk = new QQMapWX({key: app.globalData.map_key});//解析地址
Page({
  data: {
    nav:{top:app.globalData.nav_top,title:'地图导航',home:'show',back:'show',safe_top:app.globalData.safe_top},page:1,img_replace:0,map_show:1,marker:[],setting:{},show_shop:'',ac:'list',scale:18
  },

  onLoad: function (op) {//ac值 postion 为选点 list为门店列表 输入坐标值 则直接导航
    var id=op.id;//门店的id
    if(!id){id=0;}this.data.id=id;
var ac=op.ac;if(!ac){ac='list';}
let latitude=op.latitude;let longitude=op.longitude;
if(!latitude){
  latitude=op.lat;longitude=op.lng;
}
if(latitude && longitude){
  console.log('导航')
  this.setData({longitude:longitude,latitude:latitude,ac:'daohang'})
}else{
  this.setData({ac:ac});//导航还是选点
}
  },


  onReady: function () {
    var id=this.data.id;if(!id){id=0;}
    var setting=this.data.setting;
    var ac=this.data.ac;
    fun.get_pos().then(res=>{
      if(res.err!='ok'){app.msg('请打开位置信息获取最近门店');return;}//错误
      app.globalData.latitude=res.latitude;
      app.globalData.longitude=res.longitude;

switch(ac){
default:
  fun.get({ac:'get_shop_list',longitude:res.longitude,latitude:res.latitude,id:id,path:''}).then(res=>{
    var marker=[];
   for(var i in res.shop_list){
     var s=res.shop_list[i];
     var width='50px';var marker_id=0;
     if(s.id==res.shop.id){var icon='/pages/img/location.png';
     setting.latitude=s.latitude;setting.longitude=s.longitude;marker_id=i;
   }else{var icon='/pages/img/point.png';width='30px'}
     marker.push({id:parseInt(i),longitude:s.longitude,latitude:s.latitude,iconPath:icon,width:width,height:width,title:s.shop_name})
   }
   if(app.globalData.latitude){
     marker.push({id:999,latitude:app.globalData.latitude,longitude:app.globalData.longitude,iconPath:'/pages/img/p.png',width:'50px',height:'50px'})
   }
   console.log(marker)
           this.setData({list:res.shop_list,shop:res.shop,marker:marker,setting:setting,marker_id:marker_id,latitude:setting.latitude,longitude:setting.longitude});
           this.load();
         })
break;//门店
case 'daohang'://导航到点
var latitude=this.data.latitude;var longitude=this.data.longitude;
this.get_pos(latitude,longitude,1);
break;
case 'position': this.get_pos(res.latitude,res.longitude);//定位
break;
}

      })
   
  },
 
  async  get_pos(latitude,longitude,daohang){//获取选点位置
  var that=this;var shop={}; var setting=this.data.setting;
  qqmapsdk.reverseGeocoder({
    location:{latitude:latitude,longitude:longitude},
    success(res){
      console.log(res);
shop.addr=res.result.address;
shop.shot_name=res.result.formatted_addresses.recommend;
shop.latitude=latitude;
shop.longitude=longitude;
var marker=that.data.marker;if(!marker){marker=[]}
var has=0;
for(var i in marker){
  if(marker[i].id==999){has++;
    marker[i].latitude=latitude;
    marker[i].longitude=longitude;
  }
}
if(has==0){
marker.push({id:999,latitude:latitude,longitude:longitude,iconPath:'/pages/img/p.png',width:'50px',height:'50px',label:{content:shop.shot_name,textAlign:'center'}});
}

setting.latitude=latitude;setting.longitude=longitude;
that.setData({marker:marker,setting:setting,latitude:setting.latitude,longitude:setting.longitude,shop:shop});
if(daohang==1){
  that.daohang()
}
    }

  })
},
regionchange(e){//拖到地图
if(e.type=='end' && e.detail.causedBy=="drag"){
  var ac=this.data.ac;
  if(ac=='position'){
    this.get_pos(e.detail.centerLocation.latitude,e.detail.centerLocation.longitude)
  }
}


},


  onShow: function () {

  },
load(){

},
select_this_point(e){//点击选择门店
  var ac=this.data.ac;
  console.log(e.detail.markerId);
  var c=e.currentTarget.dataset.c;
  if(c){var markerId=e.currentTarget.dataset.index;
  }else{ var markerId=e.detail.markerId;}
switch(ac){
  default:
    var marker_id=this.data.marker_id;if(!marker_id){marker_id=0;}
    if(markerId==999){return;}
    var list=this.data.list;
    var setting=this.data.setting;
    var marker=this.data.marker;
    marker[marker_id].iconPath='/pages/img/point.png';
    marker[marker_id].width='30px';marker[marker_id].height='30px';
    marker_id=markerId;
    marker[marker_id].iconPath='/pages/img/location.png';
    marker[marker_id].width='50px';marker[marker_id].height='50px';
    setting.latitude=marker[marker_id].latitude;setting.longitude=marker[marker_id].longitude;
    var shop=list[markerId];
    this.setData({marker:marker,setting:setting,marker_id:marker_id,shop:shop,latitude:shop.latitude,longitude:shop.longitude,polyline:[],scale:18});    
break;//列表
case 'position':
  var marker=this.data.marker;
if(marker){
for(var i in marker){
if(marker[i].id==999){
  marker[i].latitude=marker[markerId].latitude;
  marker[i].longitude=marker[markerId].longitude;
}

}
this.setData({marker:marker})
this.get_pos(marker[markerId].latitude,marker[markerId].longitude);
}break;
}


},
  onHide: function () {

  },
  moveToLocation(e){//到原点
    var ac=this.data.ac;
switch(ac){
  default:
    var setting=this.data.setting;
  setting.latitude=app.globalData.latitude;setting.longitude=app.globalData.longitude;
this.setData({setting:setting,latitude:app.globalData.latitude,longitude:app.globalData.longitude});  
  break;
case 'position':this.get_pos(app.globalData.latitude,app.globalData.longitude);break;
}

  },
  select_shop_location(e){var that=this;
var shop=this.data.shop;console.log(shop)
var setting=this.data.setting;
setting.latitude=shop.latitude;setting.longitude=shop.longitude;
this.setData({setting:setting,latitude:shop.latitude,longitude:shop.longitude});

  },
  daohang(e){//获取导航路径
    var _this=this;
    var shop=this.data.shop;
    //var qqmapsdk = new QQMapWX({key: app.globalData.map_key});
    var is_get_daohang=this.data.is_get_daohang;
    if(is_get_daohang==1){return;}
    this.data.is_get_daohang=1;
    app.msg('导航计算中，请稍后...');
    qqmapsdk.direction({
      mode: 'driving',
      from: {latitude:app.globalData.latitude,longitude:app.globalData.longitude},
      to: {latitude:shop.latitude,longitude:shop.longitude}, 
      success: function (res) {
console.log(res)
_this.data.is_get_daohang=0;
var ret = res;
shop.distance=res.result.routes[0].distance;//距离
if(shop.distance>500){shop.distance=fun.number_fromat(shop.distance/1000,2)+'千米';}else{
  shop.distance=shop.distance+'米';
}
var time=res.result.routes[0].duration;
if(time>60){
var hour=Math.floor(time/60);
var min=time-hour*60;
shop.time=hour+'小时'+min+'分';
}else{
  shop.time=time+'分钟';
}
var coors = ret.result.routes[0].polyline, pl = [],colorList=[];
//坐标解压（返回的点串坐标，通过前向差分进行压缩）
var kr = 1000000;
for (var i = 2; i < coors.length; i++) {
  coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
}
//将解压后的坐标放入点串数组pl中
for (var i = 0; i < coors.length; i += 2) {
  pl.push({ latitude: coors[i], longitude: coors[i + 1] });
//var color=_this.get_color(i,coors.length);

  if(i>0){
 // colorList.push(color);
}
}
console.log(pl,colorList)
//设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点

_this.setData({
  latitude:pl[0].latitude,
  longitude:pl[0].longitude,
 shop:shop,
 scale:14,
  polyline: [{
    points: pl,
    color: '#00a47cDD',
    //colorList:colorList,
    width:6
  }]
})

      }
    });


  },
  key_input(e){
var val=e.detail.value;
this.setData({key:val})
  },
  search_this(e){//关键词查找列表
    var key=this.data.key;if(!key){app.msg('请输入需要查找的关键词');return;}
    var marker=[];var that=this;
    qqmapsdk.search({
      keyword:key,
      page_size:20,
      auto_extend:0,//不扩大区域
      success(res){
        console.log(res)
        for (var i = 0; i < res.data.length; i++) {
          marker.push({ // 获取返回结果，放到mks数组中
            shot_name: res.data[i].title,
            addr:res.data[i].address,          
            id: i,
            latitude: res.data[i].location.lat,
            longitude: res.data[i].location.lng,
            iconPath: "/pages/img/point.png", //图标路径
            width:30,
            height:30
          });
        
        }
that.setData({marker:marker})
      }
    })

  },
  select_this_position(e){//选择点的信息
var shop=this.data.shop;
if(!shop){app.msg('请选择您的位置');return;}
var that=this;
qqmapsdk.reverseGeocoder({
  location:{latitude:shop.latitude,longitude:shop.longitude},
  success(res){
    console.log(res.result);
app.globalData.is_select_position=res.result;
that.back();
  }

})




  },
  onUnload: function () {

  },


  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },go(e){ 
    var url=e.currentTarget.dataset.url;
    if(!url){app.msg('没有设置链接，请到后台设置或者联系我们');return;}
    wx.navigateTo({url: e.currentTarget.dataset.url})},
  back(e){wx.navigateBack({delta:0})},
  home(e){ wx.reLaunch({url: '/pages/index/index'})},
  rgo(e){wx.redirectTo({url: e.currentTarget.dataset.url})},
  login: function (e) { wx.navigateTo({url: '/pages/login/index'})},
  win_open(e){var c=e.currentTarget.dataset.c;this.setData({[c]:'show'})},//打开窗口
  win_close(e){var c=e.currentTarget.dataset.c;this.setData({[c]:''})},//关闭窗口
open_min(e){wx.navigateToMiniProgram({appId: e.currentTarget.dataset.url,path: '/pages/index/index',})},
scan(e){fun.scan();},call(e){
var list=this.data.list;
var index=e.currentTarget.dataset.index;
wx.makePhoneCall({
  phoneNumber: list[index].phone,
})

},get_color(i,length){
var val='0123456789abcdef';
var re='#';
for(var i=0;i<=5;i++){
re+=val[Math.floor(Math.random()*16)]
}
return re;

} 
})


